package org.example.sync.safe;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author zhengdp
 * @Description 卖票练习
 * @Date 2022/9/25 22:37
 * @Created by zhengdp
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {

    public static void main(String[] args) {
        // 对象被多个线程共享
        TicketWindow ticketWindow = new TicketWindow(5000);
        List<Thread> list = new ArrayList<>();
        // 用来存储卖出去多少张票 (线程安全类）
        List<Integer> sellCount = new Vector<>();
        for(int i =0;i<5000;i++){
            Thread t = new Thread(() -> {
                int count = ticketWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 卖出去的票求和
        log.info("selled count : {}",sellCount.stream().mapToInt(item -> item).sum());
        // 剩余票数
        log.info("remainder count : {}",ticketWindow.getCount());
    }

    static Random random  = new Random(System.currentTimeMillis());

    public static int randomAmount(){
        return random.nextInt(5) + 1;
    }

    // 买票窗口
    static class TicketWindow {
        private int count ;

        public TicketWindow(int count ) {
            this.count = count;
        }

        public int getCount() {
            return  count;
        }

        public int sell(int amount) {
            if(this.count >= amount) {
                this.count -= amount;
                return  amount;
            } else {
                return  0;
            }
        }
    }
}
